package com.network.dao;

import java.util.ArrayList;

import org.apache.commons.lang.xwork.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;

import com.network.entity.Page;
import com.network.entity.User;
import com.network.entity.UserQryHelper;

/**
 * UserDAO和Hibernate实现
 * 
 * @author Ling Xiaowei
 * 
 */
@Component
public class UserDAOImpl extends HibernateGeneticTemplate implements IUserDAO {

	public void saveOrUpdateUser(User user) {
		this.getHibernateTemplate().saveOrUpdate(user);
	}

	public void deleteUser(User user) {
		this.getHibernateTemplate().delete(user);
	}

	public User getUserById(String id) {
		return (User) this.getHibernateTemplate().get(User.class, id);
	}

	public void deleteUserById(String id) {
		
		User user = getUserById(id);
		if (user != null) {
			this.getHibernateTemplate().delete(user);
		}
		else
		{
			//Do nothing
		}
	}

	public boolean isUsernameExisted(String id) {
		
		if(getUserById(id) != null)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
	public ArrayList<User> loadUser(Page p, UserQryHelper helper) {
		// TODO Auto-generated method stub
		getRecordNum(p,helper);
		Criteria criteria = this.buildCriteria(helper);
		System.out.println(p.getTotalRecNum());
		System.out.println(helper);
		System.out.println("开始:"+p.getStartIndex()+" 条数:"+p.getPageSize());
		ArrayList<User> l = (ArrayList<User>)criteria.setMaxResults(p.getPageSize()).setFirstResult(p.getStartIndex()).list();

		System.out.println("获得记录条数："+l.size());

		return l;
	}

	public void getRecordNum(Page p, UserQryHelper helper) {
		// TODO Auto-generated method stub
		Criteria criteria = this.buildCriteria(helper);

		Long i =  (Long) criteria.setProjection(
                Projections.rowCount()).uniqueResult();
		p.setTotalRecNum(i.intValue());
		System.out.println("i is : "+i);
		criteria.setProjection(null);
	}
	
	public Criteria buildCriteria(UserQryHelper helper) {
		// TODO Auto-generated method stub
		Criteria criteria = this.getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(User.class);
		
		if(StringUtils.isNotEmpty(helper.getName()))
		{
			criteria.add(Restrictions.eq("name", helper.getName()));
		}
		else if(StringUtils.isNotEmpty(helper.getSchool()))
		{
			criteria.add(Restrictions.eq("school", helper.getSchool()));
		}
		else if(StringUtils.isNotEmpty(helper.getCollege()))
		{
			criteria.add(Restrictions.eq("college", helper.getCollege()));
		}
		else if(StringUtils.isNotEmpty(helper.getRole()))
		{
			criteria.add(Restrictions.eq("role", helper.getRole()));
		}
		else
		{
			//do nothing
		}

		return criteria;
	}
	

}
